﻿#include "rtprecv.h"

RTPRecv::RTPRecv(QObject *parent) : QThread(parent)
{
    // 初始化音视频接收队列
    isRun = false;

    fifoBufferVideo = new FiFoBuffer();
    fifoBufferVideo->initFiFoBuffer(3*1024*1024);

    fifoBufferAudio = new FiFoBuffer();
    fifoBufferAudio->initFiFoBuffer(1*1024*1024);
}

RTPRecv::~RTPRecv()
{
    // 销毁音视频接收队列
    isRun = false;

    delete fifoBufferVideo;
    fifoBufferVideo = nullptr;

    delete fifoBufferAudio;
    fifoBufferAudio = nullptr;

    quit();
    wait();
}

void RTPRecv::setRunState(bool start)
{
    isRun = start;

    if(start)
        this->start();
}

void RTPRecv::resetRecvBuffer()
{
    fifoBufferAudio->resetFiFoBuffer();
    fifoBufferVideo->resetFiFoBuffer();
}

void RTPRecv::run()
{
    // 运行这个RTP接受者线程，不断通过udp读取出RTP包，并分别放入视频接收队列、音频接收队列

    QUdpSocket udpSocket; //视频 udp port:8554
    udpSocket.bind(QHostAddress::AnyIPv4, 8554);

    QUdpSocket udpSocketAudio; //音频 udp port:8555
    udpSocketAudio.bind(QHostAddress::AnyIPv4, 8555);

    char udpData[1500] = {0}; //视频
    char udpDataAudio[1500] = {0}; //音频

    while (isRun)
    {
        if(udpSocket.hasPendingDatagrams())
        {
            memset(udpData, 0, 1500);
            qint64 len = udpSocket.readDatagram(udpData, 1500);
            fifoBufferVideo->pushData(udpData, len); //读取视频RTP包到视频接收队列中
        }

        if(udpSocketAudio.hasPendingDatagrams())
        {
            memset(udpDataAudio, 0, 1500);
            qint64 len = udpSocketAudio.readDatagram(udpDataAudio, 1500);
            fifoBufferAudio->pushData(udpDataAudio, len); //读取音频RTP包到音频接收队列中
        }

        QThread::msleep(1);
    }
}
